<template>
  <van-dropdown-menu ref="iFilter" swipe-threshold="4">
    <van-dropdown-item
      v-for="$item in filterList"
      :key="$item.key"
      :title="$item.title"
      v-model="$item.initialValue"
      :options="$item.option"
      @change="confirm"
    >
      <!-- title slot -->
      <template v-if="$item.customTitle" #title>
        <slot :name="`${$item.key}-title`"></slot>
      </template>
      <!-- value solt -->
      <slot :name="$item.sortName"></slot>
      <!-- 基础筛选配置 -->
      <template v-if="$item.key === 'filter'">
        <van-cell-group class="filter-value-wrap">
          <van-cell
            v-for="$e in $item.list"
            :key="$e.key"
            :title="$e.title"
            :class="$e.type === 'input' ? 'row' : 'column'"
          >
            <i-input v-if="$e.type === 'input'" v-model="$e.initialValue"></i-input>
            <i-checkboxbutton
              v-if="$e.type === 'checkboxbutton'"
              v-model="$e.initialValue"
              :itemList="$e.itemList"
            >
            </i-checkboxbutton>
            <i-radio
              v-if="$e.type === 'radio'"
              v-model="$e.initialValue"
              :itemList="$e.itemList"
            ></i-radio>
          </van-cell>
        </van-cell-group>
        <div class="filter-btn">
          <van-button @click="reset">重置</van-button>
          <van-button type="primary" @click="confirm">确定</van-button>
        </div>
      </template>
    </van-dropdown-item>
  </van-dropdown-menu>
</template>

<script setup name="i-filter">
import { ref, toRaw } from 'vue'

const emit = defineEmits(['handle-filter'])
const props = defineProps({
  list: {
    type: Array,
    required: true,
    default: () => []
  }
})
const iFilter = ref(null)
const filterList = ref(props.list)
// 格式化查询数据
const formatData = () => {
  const data = {}
  filterList.value.forEach((e) => {
    if (e.key !== 'filter') data[e.key] = toRaw(e.initialValue)
    else {
      e.list.forEach((el) => {
        data[el.key] = toRaw(el.initialValue)
      })
    }
  })
  return data
}
// 重置
const reset = () => {
  filterList.value = filterList.value.map((e) => {
    if (e.key === 'filter') {
      e.list.forEach((el) => {
        if (['checkboxbutton'].includes(el.type)) el.initialValue = []
        else el.initialValue = ''
      })
      return e
    }
    return e
  })
  confirm()
}
// 确定/查询
const confirm = () => {
  iFilter.value.close()
  const data = formatData()
  emit('handle-filter', data)
}
</script>

<style lang="less" scoped>
.filter-value-wrap {
  .van-cell {
    &.column {
      flex-direction: column;
    }
    &.row {
      flex-direction: row;
      align-items: center;
    }
    /deep/ input {
      text-align: right;
    }
  }
}
.filter-btn {
  display: flex;
  button {
    flex: 1;
  }
}
</style>